package com.xingkeduo.business.transformation.json;

import com.fasterxml.jackson.databind.JsonNode;
import com.xingkeduo.pojo.query.ConsumerFileQO;
import com.xingkeduo.pojo.table.ConsumerFileTO;
import com.xingkeduo.util.pojo.base.BaseJson;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.InputParamException;
import com.xingkeduo.util.tool.CommonUtil;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @Author:gaozifeng
 * @Date 2019/3/26 19:29
 **/
@Component
public class ConsumerFileJTO extends BaseJson {

    public static ConsumerFileTO createTableForNew(String json) throws Throwable {
        ConsumerFileTO table = new ConsumerFileTO();
        JsonNode root = validJson(json);
        if (root == null) {
            throw new InputParamException(InputParamException.Type.INVALID, "参数");
        }
        table.setPath(validString(root,"path",300, YesNoEnum.NO)).setType(validType(root,YesNoEnum.NO)).setConsumerId(validPrimary(root,"consumerId",YesNoEnum.NO));
        return table;
    }


    public static ConsumerFileQO createQueryForPrimary(String json) throws Throwable {
        ConsumerFileQO query = new ConsumerFileQO();
        JsonNode root = validJson(json);
        if (root == null)
            throw new InputParamException(InputParamException.Type.INVALID, "参数");
        query.setId(validId(root, YesNoEnum.YES));
        return query;
    }

    public static int validType(JsonNode node, YesNoEnum isRequired) throws Throwable {
        String key = "type";
        if (YesNoEnum.YES == isRequired && !node.has(key))
            throw new InputParamException(InputParamException.Type.NULL, key);

        if (node.has(key)) {
            String value = node.path(key).asText().trim();
            if (CommonUtil.isEmpty(value) || value.length() > 2)
                throw new InputParamException(InputParamException.Type.INVALID, key + " error");
            return Integer.valueOf(value);
        }
        return 0;
    }
}
